/*************************************************************************
	> File Name: 5.HZOJ-532.cpp
	> Author: hug
	> Mail: hug@haizeix.com
	> Created Time: 四  2/13 09:12:38 2025
 ************************************************************************/

#include <iostream>
#include <queue>
#include <cstring>
using namespace std;

struct Data {
    int x, y;
};

int n, m, total = 0, sx, sy;
int h[505][505], a[505][505], vis[505][505];
int dir[4][2] = {
    {0, 1}, {1, 0}, {0, -1}, {-1, 0}
};

int bfs(int max_) {
    int cnt = 0;
    memset(vis, 0, sizeof(vis));
    queue<Data> q;
    q.push({sx, sy});
    vis[sx][sy] = 1;
    while (!q.empty()) {
        Data cur = q.front();
        q.pop();
        cnt += a[cur.x][cur.y];
        for (int i = 0; i < 4; i++) {
            int dx = cur.x + dir[i][0];
            int dy = cur.y + dir[i][1];
            if (dx < 1 || dx > n || dy < 1 || dy > m) continue;
            if (abs(h[cur.x][cur.y] - h[dx][dy]) > max_) continue;
            if (vis[dx][dy]) continue;
            vis[dx][dy] = 1;
            q.push({dx, dy});
        }
    }
    return cnt;
}

int erfen() {
    int l = 0, r = (int)1e9, mid;
    while (l < r) {
        mid = (l + r) / 2;
        if (bfs(mid) < total) l = mid + 1;
        else r = mid;
    }
    return l;
}

int main() {
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            cin >> h[i][j];
        }
    }
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            cin >> a[i][j];
            total += a[i][j];
            if (a[i][j] == 1) sx = i, sy = j;
        }
    }
    cout << erfen() << endl;
    return 0;
}
